package com.ee.chat.api.advice;

import com.google.gson.GsonBuilder;
import com.ndhutu.ee.util.encrypt.AESUtil2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * Author:Bobby
 * DateTime:2019/4/9
 **/
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Value("${spring.profiles.active}")
    String active;
    @Value("${encrypt.aesKey}")
    String aesKey;

    //需要过滤的请求
    static List<String> urls;
    static{
        String[] urlArrs = new String[]{"/payNotify/wxPayNotify", "/payNotify/aliPayNotify", "/payNotify/zfpaiPayNotify",
                "/payNotify/yfkPayNotify", "/payNotify/zunPayNotify", "/payNotify/pay96Notify", "/payNotify/fylPayNotify",
                "/im/imCallback", "/im/imCopyCallback",
                "/base/getNewestVersion", "/base/ossCallback", "/base/addClickLog"};
        urls = Arrays.asList(urlArrs);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String path = new String(request.getRequestURI().getBytes());
        String url = path.substring(path.indexOf("/", 1));

        //测试接口专用
        String dev = request.getParameter("dev");

        if(urls.indexOf(url) >= 0 || "1".equals(dev)){
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
//            String content = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);
            String content = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create().toJson(body);
//            String result = AESUtil.encrypt(content, aesKey);
            String result = AESUtil2.aesEncrypt(content, aesKey);
//            AES aes = SecureUtil.aes(aesKey.getBytes());
//            String result = aes.encryptHex(content);
//            String result = AESUtil3.encrypt(content, aesKey);
//            log.info("Pre-encrypted data：{}，After encryption：{}", content, result);
//            log.info("返回结果加密已完成");
            return result;
        } catch (Exception e) {
            log.error("Encrypted data exception", e);
        }
        return body;
    }
}
